use rusqlite::params;

use crate::dao;
use crate::models::models::components::v2ray::subscription::{ComponentV2raySubscription, ComponentV2raySubscriptionLastUpdateState};
use crate::runtime::error::MagicBoxError;
use crate::runtime::response::Code;
use crate::runtime::result::MagicBoxResult;

/// 保存订阅配置
pub(crate) fn save_subscription_config(subscription: ComponentV2raySubscription) -> MagicBoxResult<()> {
    let connection = dao::connection::components::v2ray();

    // 检查是否存在
    let result = connection.prepare("select uuid from subscriptions where uuid = ?1 limit 1").unwrap().query_row([&subscription.uuid], |row| {
        Ok(row.get::<_, String>(0)?)
    });

    // 存在则更新
    if result.is_ok() {
        let mut statement = connection.prepare("update subscriptions set name = ?2, url = ?3, enabled = ?4, auto_update = ?5 where uuid =?1").unwrap();
        let result = statement.execute(params![subscription.uuid, subscription.name, subscription.url, subscription.enabled, subscription.auto_update]);
        if result.is_err() {
            let err = result.unwrap_err().to_string();
            log::error!("更新订阅配置失败: {}", err.as_str());

            return Err(MagicBoxError::new(Code::UndefinedError, format!("更新订阅配置失败: {}", err.as_str()).as_str()));
        }

        return Ok(());
    }

    // 插入数据
    let mut statement = connection.prepare("insert into subscriptions (uuid, name, url, enabled, auto_update) values (?1, ?2, ?3, ?4, ?5)").unwrap();
    let result = statement.execute(params![subscription.uuid, subscription.name, subscription.url, subscription.enabled, subscription.auto_update]);
    if result.is_err() {
        let err = result.unwrap_err().to_string();
        log::error!("保存订阅配置失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, format!("保存订阅配置失败: {}", err.as_str()).as_str()));
    }

    Ok(())
}

/// 删除订阅配置
pub(crate) fn remove_subscription_config(uuid: String) -> MagicBoxResult<()> {
    let connection = dao::connection::components::v2ray();

    let mut statement = connection.prepare("delete from subscriptions where uuid = ?1").unwrap();
    let result = statement.execute(params![uuid]);
    if result.is_err() {
        let err = result.unwrap_err().to_string();
        log::error!("删除订阅配置失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, format!("删除订阅配置失败: {}", err.as_str()).as_str()));
    }

    Ok(())
}

/// 获取订阅列表
pub(crate) fn get_subscription_configs() -> MagicBoxResult<Vec<ComponentV2raySubscription>> {
    let connection = dao::connection::components::v2ray();
    let mut subscriptions: Vec<ComponentV2raySubscription> = Vec::new();

    let mut statement = connection.prepare("select * from subscriptions order by id desc").unwrap();
    let result = statement.query_map([], parse_to_subscription);

    if result.is_err() {
        let err = result.err().unwrap().to_string();
        log::error!("获取订阅列表失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, format!("获取订阅列表失败: {}", err.as_str()).as_str()));
    }

    let result = result.unwrap();
    for subscription in result {
        if subscription.is_err() {
            let err = subscription.err().unwrap().to_string();
            log::error!("获取订阅失败: {}", err.as_str());

            return Err(MagicBoxError::new(Code::UndefinedError, format!("获取订阅失败: {}", err.as_str()).as_str()));
        }

        subscriptions.push(subscription.unwrap());
    }

    Ok(subscriptions)
}

/// 更新配置的最后更新时间
pub(crate) fn update_last_update_time(subscription: &ComponentV2raySubscription, time: i64, state: ComponentV2raySubscriptionLastUpdateState) -> MagicBoxResult<()> {
    let connection = dao::connection::components::v2ray();

    let mut statement = connection.prepare("update subscriptions set last_update_time = ?2, last_update_state = ?3 where uuid =?1").unwrap();
    let result = statement.execute(params![subscription.uuid, time, state]);
    if result.is_err() {
        let err = result.unwrap_err().to_string();
        log::error!("更新订阅配置的最后更新时间失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, format!("更新订阅配置的最后更新时间失败: {}", err.as_str()).as_str()));
    }

    return Ok(());
}

/// 解析订阅配置
fn parse_to_subscription(row: &rusqlite::Row) -> rusqlite::Result<ComponentV2raySubscription> {
    let mut subscription = ComponentV2raySubscription::default();

    subscription.uuid = row.get::<_, String>(1)?;
    subscription.name = row.get::<_, String>(2)?;
    subscription.url = row.get::<_, String>(3)?;
    subscription.enabled = row.get::<_, bool>(4)?;
    subscription.auto_update = row.get::<_, bool>(5)?;
    subscription.last_update_time = row.get::<_, i64>(6)?;
    subscription.last_update_state = row.get::<_, ComponentV2raySubscriptionLastUpdateState>(7)?;

    Ok(subscription)
}